module.exports = app => {
  const express = require('express')
  const db = require('mongoose')
  const router = express.Router()
  const ObjectId = require('mongodb').ObjectId
  app.use(express.json()) // 使用json

  // 模糊查询 分页
  router.get('/tableTest/page', async (req, res) => {
    let { page, limit, name, field, order } = req.query
    const query = table.find({})
    query.sort({ createDate: order || -1 }) //  -1降序 1升序
    if (!page) page = 1
    if (!limit) limit = 10
    if (name) { // 模糊查询
      const qs = new RegExp(name)
      query.where(field, qs)
    }
    query.skip((page - 1) * limit)
    query.limit(Number(limit))
    query.exec((err, data) => {
      if (err) {
        console.log(err)
      } else {
        table.find((err, result) => { // 计算数据总数
          const list = {
            data: data,
            code: err ? 1 : 0,
            msg: err || 'success',
            total: name ? data.length : result.length
          }
          res.json(list)
        })
      }
    })
  })

  // 查询单个
  router.get('/tableTest/:id', async (req, res) => {
    const data = await table.findById(req.params.id)
    res.send({
      code: 0,
      msg: 'success',
      data
    })
  })

  // 删除
  router.delete('/tableTest', async (req, res) => {
    req.body.forEach(item => {
      table.findOneAndDelete({ _id: ObjectId(item) }, () => {})
    })
    res.send({
      code: 0,
      msg: '删除成功'
    })
  })

  // 新增
  router.post('/tableTest', async (req, res) => {
    const timeNow = new Date()
    const data = await table.create({ ...req.body, createDate: timeNow })
    res.send({
      code: 0,
      msg: 'success',
      data
    })
  })

  // 修改
  router.put('/tableTest', async (req, res) => {
    const timeNow = new Date()
    await table.findByIdAndUpdate(ObjectId(req.body._id), { ...req.body, upDate: timeNow })
    res.send({
      code: 0,
      msg: 'success'
    })
  })
  
  // 增加评论
  router.put('/tableTest/comment', async (req, res) => {
    const timeNow = new Date()
    const data = await table.findById(req.body.id)
    await table.findByIdAndUpdate(ObjectId(req.body.id), { 
      ...data,
      comment: data.comment.push(req.body.comment),
      upDate: timeNow,
    })
    res.send({
      code: 0,
      data: data.comment,
      msg: 'success'
    })
  })

  // 建表测试
  const table = db.model('tableTest', new db.Schema({
    name: { type: String },
    content: { type: String },
    day: { type: String },
    local: { type: String },
    time: { type: String },
    title: { type: String },
    uploader: { type: String },
    createDate: { type: String },
    comment: { type: Array },
    upDate: { type: String }
  }))

  app.use('/node/api', router)
}
